package com.xinshujia.config.authentication.filter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xinshujia.utils.GsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author: 野狼上校
 * @since: 2024-08-03 13:24
 * @version: 1.0
 * @descript:
 */
@Component
public class MyLoginFilter extends UsernamePasswordAuthenticationFilter {
 @Override
 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  if (!request.getMethod().equals("POST")) {
   throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  }

  if(request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)){
   Gson gson = GsonUtil.googleGson();
   try {
    Map<String, String> userInfo = gson.fromJson(new InputStreamReader(request.getInputStream()), new TypeToken<Map<String, String>>(){}.getType());
    String username = userInfo.get(getUsernameParameter());
    String password = userInfo.get(getPasswordParameter());

    UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
            password);
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
    return this.getAuthenticationManager().authenticate(authRequest);
   } catch (IOException e) {
    throw new RuntimeException(e);
   }

  }

  return super.attemptAuthentication(request, response);
 }
}